import { defineStore } from 'pinia';
import { store } from '@/store';
import // ACCESS_TOKEN,
// CURRENT_USER,
// LOGIN_ID,
// TENANT_CODE,
// IS_LOCKSCREEN,
// TABS_ROUTES,
'@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';
import { getUserInfo, login, logout } from '@/api/system/user';
import { getMenuList } from '@/api/system/menu';
import { storage } from '@/utils/Storage';
import { useTabsViewStore } from '@/store/modules/tabsView';
// import { getApplicationConfigList } from '@/api/basicConfiguration/applicationConfiguration';

export interface IUserState {
  token: string;
  loginId: string;
  username: string;
  nickName: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: any;
  powers: any[];
  openResetPwdModal: boolean;
  tenantCode: string;
  wujieRouterPath: string;
  applicationConfigList: any[];
  applicationConfig: any;
  isGetApplication: boolean;
  virtualKeyboard: boolean;
}

const props: any = (window as any).$wujie?.props || null;

let token = storage.get('access_token') || '';

let loginId = storage.getCookie('login-id') || '';

let nickName = '';

let username = '';

let powers = [];

let tenantCode = storage.getCookie('tenant-code') || '';

if (props) {
  const { user = {} } = props;

  if (user) {
    const {
      access_token: uToken = null,
      ['login-id']: uLoginId = null,
      userInfo = null,
      powers: uPowers = null,
      tenantCode: uTenantCode = null,
    } = user;

    if (userInfo) {
      const { nickName: uNickName = null, userName: uUserName = null } = userInfo;

      uNickName && (nickName = uNickName);

      uUserName && (username = uUserName);
    }

    uToken && (token = uToken);

    uLoginId && (loginId = uLoginId);

    uPowers && (powers = uPowers);

    uTenantCode && (tenantCode = uTenantCode);
  }
}

const localStorageUserInfo = storage.get('userInfo') || null;

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token,
    nickName,
    username,
    welcome: '',
    avatar: '',
    loginId,
    permissions: [],
    info: localStorageUserInfo || null,
    powers: localStorageUserInfo?.permissions || powers,
    openResetPwdModal: false,
    tenantCode,
    wujieRouterPath: '',
    applicationConfigList: [],
    applicationConfig: null,
    isGetApplication: false,
    virtualKeyboard: !!storage.get('virtualKeyboard'),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getLoginId(): string {
      return this.loginId;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.nickName;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): object {
      return this.info;
    },
    getPowers(): [any][] {
      return this.powers;
    },
    getOpenResetPwdModal(): boolean {
      return this.openResetPwdModal;
    },
  },
  actions: {
    changeVirtualKeyboard(val) {
      this.virtualKeyboard = val;

      storage.set('virtualKeyboard', val);
    },
    setToken(token: string) {
      this.token = token;
    },
    setLoginId(loginId) {
      this.loginId = loginId;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setPowers(powers) {
      this.powers = powers;
    },
    setUserInfo(info) {
      this.info = info;
    },
    setTenantCode(tenantCode) {
      this.tenantCode = tenantCode;
    },
    // async getapplicationConfigList() {
    //   try {
    //     const { row = [] } = await getApplicationConfigList();

    //     if (row && row.length) {
    //       const obj = row.find((item) => item.usageScenarios === 'pc');

    //       if (obj) {
    //         this.applicationConfig = obj;
    //       }

    //       this.applicationConfigList = row || [];
    //     }
    //   } catch (e) {
    //     console.log(e);
    //   }

    //   this.isGetApplication = true;
    // },
    // 登录
    async login(userInfo) {
      try {
        const res = await login(userInfo);

        const { data, code } = res;

        if (code === ResultEnum.SUCCESS) {
          // const ex = 7 * 24 * 60 * 60 * 1000;

          storage.set('access_token', data);

          this.setToken(data);
        }

        return Promise.resolve(res);
      } catch (e) {
        return Promise.reject(e);
      }
    },

    // 获取用户信息
    getInfo() {
      const that = this;

      return new Promise((resolve, reject) => {
        Promise.all([getUserInfo(), getMenuList()])
          .then((res: any) => {
            const { data = null } = res[0];

            const { data: data2 = null } = res[1];

            if (data) {
              if (data2) {
                const { permissions = [], menuList = [] } = data2;

                // console.log(menuList)

                if (permissions && permissions.length) {
                  data['powers'] = permissions;
                }

                if (menuList && menuList.length) {
                  data['menuList'] = menuList;
                }
              }

              that.setUserInfo(data);
            }

            // if (row) {
            //   const { permissions = [], avatar = '' } = row;

            //   const permissionsList = permissions || [];

            //   row.menuList = res[1]?.row?.treeSelectList || [];

            //   that.setPermissions(permissionsList);

            //   that.setUserInfo(row);

            //   that.setAvatar(avatar);
            // } else {
            //   reject(new Error('getInfo: 没有返回值 !'));
            // }

            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 登出
    async logout() {
      try {
        await logout();

        this.clearAll();

        if (window.electron && window.electron.deleteChildProcess) {
          window.electron.deleteChildProcess();
        }

        // this.setPermissions([]);

        // this.setUserInfo('');

        // storage.remove('userInfo');

        // storage.remove(CURRENT_USER);

        return Promise.resolve();
      } catch (e) {
        return Promise.reject(e);
      }
    },

    setOpenResetPwdModal(boolean: boolean): void {
      this.openResetPwdModal = boolean;
    },

    clearAll() {
      const tabsViewStore = useTabsViewStore();

      this.setTenantCode('');

      storage.removeCookie('tenant-code');

      // storage.remove(TENANT_CODE);

      this.setToken('');

      storage.remove('access_token');

      // storage.remove(ACCESS_TOKEN);

      this.setLoginId([]);

      storage.removeCookie('login-id');

      // storage.remove(LOGIN_ID);

      storage.removeCookie('IS-LOCKSCREEN');

      // storage.remove(IS_LOCKSCREEN);

      this.setPowers([]);

      this.setPermissions([]);

      this.setUserInfo({});

      // storage.remove(CURRENT_USER);

      // 移除标签页
      // storage.remove(TABS_ROUTES);

      storage.removeCookie('TABS-ROUTES');

      tabsViewStore.initTabs([]);
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
